from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64
from FileOperate import DataProcess


class EnDe():

    #  bytes不是32的倍数那就补足为32的倍数
    def add_to_32(self,value):
        while len(value) % 32 != 0:
            value += b'\x00'
        return value  # 返回bytes

    # str转换为bytes超过32位时处理
    def cut_value(self,org_str):
        org_bytes = str.encode(org_str)
        n = int(len(org_bytes) / 32)
        length = n
        print('bytes长度：', len(org_bytes))
        i = 0
        new_bytes = b''
        while n >= 1:
            i = i + 1
            new_byte = org_bytes[(i - 1) * 32:32 * i - 1]
            new_bytes += new_byte
            n = n - 1
            if i % 10000 == 0 :
                print("切割进度... {:.2f} ...{:>10}/{}".format((i/length), i, length))

        if len(org_bytes) % 32 == 0:  # 如果是32的倍数，直接取值
            all_bytes = org_bytes
        elif len(org_bytes) % 32 != 0 and n > 1:  # 如果不是32的倍数，每次截取32位相加，最后再加剩下的并补齐32位
             all_bytes = new_bytes + self.add_to_32(org_bytes[i * 32:])
        else:
            all_bytes = self.add_to_32(org_bytes)  # 如果不是32的倍数，并且小于32位直接补齐
        print(all_bytes)

        return all_bytes

    def cut_last(self,decrypted_text):
        res = decrypted_text.rstrip('\x00')
        print(res)
        return res

    def AES_encrypt(self,org_str, key):
        # 初始化加密器
        aes = AES.new(self.cut_value(key), AES.MODE_ECB)
        # 先进行aes加密
        encrypt_aes = aes.encrypt(self.cut_value(org_str))
        # 用base64转成字符串形式
        encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8')  # 执行加密并转码返回bytes
        print('密文：\n' + encrypted_text)
        return (encrypted_text)


    def AES_decrypt(self,secret_str, key):
        # 初始化加密器
        aes = AES.new(self.cut_value(key), AES.MODE_ECB)
        # 优先逆向解密base64成bytes
        base64_decrypted = base64.decodebytes(secret_str.encode(encoding='utf-8'))
        # 执行解密密并转码返回str
        #decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '')

        try:
            decode = aes.decrypt(base64_decrypted)
            decrypted_text = str(decode, encoding='utf-8').replace('\0', '')
        except UnicodeDecodeError:
            decrypted_text = '0'

        print('明文：\n' + decrypted_text)
        return (decrypted_text)


if __name__ == '__main__':
    org_str = 'http://mp.weixin.qq.com/s?__biz=MjM5NjAxOTU4MA==&amp;mid=3009217590&amp;idx=1&amp;sn=14532c49bc8cb0817544181a10e9309f&amp;chksm=90460825a7318133e7905c02e708d5222abfea930e61b4216f15b7504e39734bcd41cfb0a26d&amp;scene=27#wechat_redirect http://mp.weixin.qq.com/s?__biz=MjM5NjAxOTU4MA==&amp;mid=3009217590&amp;idx=1&amp;sn=14532c49bc8cb0817544181a10e9309f&amp;chksm=90460825a7318133e7905c02e708d5222abfea930e61b4216f15b7504e39734bcd41cfb0a26d&amp;scene=27#wechat_redirect' \
              'http://mp.weixin.qq.com/s?__biz=MjM5NjAxOTU4MA==&amp;mid=3009217590&amp;idx=1&amp;sn=14532c49bc8cb0817544181a10e9309f&amp;chksm=90460825a7318133e7905c02e708d5222abfea930e61b4216f15b7504e39734bcd41cfb0a26d&amp;scene=27#wechat_redirect http://mp.weixin.qq.com/s?__biz=MjM5NjAxOTU4MA==&amp;mid=3009217590&amp;idx=1&amp;sn=14532c49bc8cb0817544181a10e9309f&amp;chksm=90460825a7318133e7905c02e708d5222abfea930e61b4216f15b7504e39734bcd41cfb0a26d&amp;scene=27#wechat_redirect'

    key = 'e22b28f2c9011d39e03f5b8fc3b50cd6'
    EnDe().cut_value(org_str)

    # 秘钥
    key_path = '../data/crypto/key/splitKey/part_0.csv'
    dict = DataProcess().readData(key_path,'key')
    for id ,key in dict.items():
        print(id,'---',key)

        secret_str = EnDe().AES_encrypt(org_str, key) # <class 'str'>
        
        cipher_path = '../data/test/ciphertext.txt'
        DataProcess().writeData(cipher_path,secret_str,'cipher')
        #EnDe().storeCipher(cipher_path,secret_str)
        decrypted_text = EnDe().AES_decrypt(secret_str,key)



